﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace HYRElectric.WirePlace
{
	[Transaction(TransactionMode.Manual)]
	internal class CmdInterruptWire : IExternalCommand
	{
		[DllImport("user32.dll")]
		public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			WindowHandle windowHandle = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			DistanceSetupForm distanceSetupForm = new DistanceSetupForm(windowHandle);
			distanceSetupForm.Show(windowHandle);
			int wMsg = 7;
			CmdInterruptWire.SendMessage(windowHandle.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			WireCollector wireCollector = new WireCollector(activeUIDocument);
			WireProcessor wireProcessor = new WireProcessor(document);
			for (;;)
			{
				try
				{
					wireCollector.Length = (double)distanceSetupForm.GetDistance() / this.m_dFeetToMM;
					CollecteWireResult collecteWireResult = wireCollector.ChoosePoint();
					if (collecteWireResult == CollecteWireResult.WithoutPoint)
					{
						continue;
					}
					if (collecteWireResult != CollecteWireResult.WithoutWire)
					{
						wireProcessor.Length = (double)distanceSetupForm.GetDistance() / this.m_dFeetToMM;
						wireProcessor.InterPoint = wireCollector.m_InterruptPoint;
						wireProcessor.TargetWire = wireCollector.m_TargetWire;
						wireProcessor.InterruptHostWire();
						continue;
					}
				}
				catch (Exception)
				{
					distanceSetupForm.Close();
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				break;
			}
			distanceSetupForm.Close();
			return Autodesk.Revit.UI.Result.Failed;
		}

		private double m_dFeetToMM = 304.8;
	}
}
